package com.gzhu.knowledgeAdmin.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzhu.knowledgeAdmin.common.exception.BusinessException;
import com.gzhu.knowledgeAdmin.common.exception.GuliException;
import com.gzhu.knowledgeAdmin.common.result.ErrorCode;
import com.gzhu.knowledgeAdmin.common.vo.OneLevel;
import com.gzhu.knowledgeAdmin.common.vo.PageVo;
import com.gzhu.knowledgeAdmin.common.vo.TypeTreeVo;
import com.gzhu.knowledgeAdmin.entity.Zs;
import com.gzhu.knowledgeAdmin.service.ZsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.gzhu.knowledgeAdmin.dao.ZsflDao;
import com.gzhu.knowledgeAdmin.entity.Zsfl;
import com.gzhu.knowledgeAdmin.service.ZsflService;


@Service("zsflService")
public class ZsflServiceImpl extends ServiceImpl<ZsflDao, Zsfl> implements ZsflService {

    @Autowired
    private ZsService zsService;


    @Override
    public PageVo queryPage(Map<String, Object> params) {
        // 获取当前页和每页大小
        long pageNo = Long.parseLong((String) params.get("page"));
        long pageSize = Long.parseLong((String) params.get("limit"));

        Page<Zsfl> page = new Page<>(pageNo, pageSize);
        QueryWrapper<Zsfl> wrapper = new QueryWrapper<>();

        baseMapper.selectPage(page, wrapper);

        return new PageVo(page);
    }

    /*
     * 查出所有分类以及子分类，以树形结构返回
     * */
    @Override
    public List<TypeTreeVo> getTree() {

        // 1、查出所有分类
        List<Zsfl> categoryList = baseMapper.selectList(null);

        // 2.查出所有一级分类
        List<TypeTreeVo> typeTreeVoList = categoryList.stream().
                filter(category -> category.getSjflid() == 0)
                .map(oneMenu -> {
                    // 通过复制，设置属性
                    TypeTreeVo typeTreeVo = new TypeTreeVo();
                    BeanUtils.copyProperties(oneMenu, typeTreeVo);

                    // 设置子分类
                    typeTreeVo.setChildren(getChildren(typeTreeVo, categoryList));
                    return typeTreeVo;
                }).collect(Collectors.toList());

        return typeTreeVoList;
    }

    @Override
    public void saveZsfl(Zsfl zsfl) {
        // 查询上一级分类信息
        Integer supKtypeId = zsfl.getSjflid();

        // 添加的是一级分类
        if (supKtypeId == 0) {
            zsfl.setFljb(1);
        } else {

            Zsfl supType = baseMapper.selectById(supKtypeId);

            // 最多添加到3级分类
            if (supType.getFljb() == 3) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }

            // 设置分类级别
            zsfl.setFljb(supType.getFljb() + 1);
        }


        baseMapper.insert(zsfl);
    }

    @Override
    public void removeZsflByIds(List<Integer> ids) {
        for (Integer id : ids) {
            // 先判断是否为最底层的分类
            Integer count = baseMapper.selectCount(new QueryWrapper<Zsfl>().eq("F_SJFLID", id));
            if (count == 0) {
                // 再判断是否被其他知识引用
                int count1 = zsService.count(new QueryWrapper<Zs>().eq("F_ZSFLID", id));
                if (count1 > 0) {
                    throw new BusinessException(ErrorCode.CATEGORY_USED);
                }
            } else {
                throw new BusinessException(ErrorCode.HAS_CHILDREN);
            }
        }


        this.removeByIds(ids);

    }

    /**
     * 获取所有一级分类
     *
     * @return
     */
    @Override
    public List<OneLevel> getAlloneLevel() {

        QueryWrapper<Zsfl> wrapper = new QueryWrapper<>();
        wrapper.eq("F_SJFLID", 0);
        List<Zsfl> oneList = baseMapper.selectList(wrapper);
        return
                oneList.stream().map(item -> {
                    OneLevel oneLevel = new OneLevel();
                    oneLevel.setFlid(item.getId());
                    oneLevel.setFlmc(item.getFlmc());
                    return oneLevel;
                }).collect(Collectors.toList());
    }

    // 获取该知识的所有分类，从第一级开始
    @Override
    public List<Integer> getAllFlIds(Zs zs) {
        List<Integer> flIds = new ArrayList<>();


        Zsfl zsfl = baseMapper.selectById(zs.getZsflid());
        flIds.add(zsfl.getId());

        while (zsfl.getSjflid() != 0) {
            zsfl = baseMapper.selectById(zsfl.getSjflid());
            flIds.add(zsfl.getId());
        }

        // 反转list
        Collections.reverse(flIds);

        return flIds;
    }


    private List<TypeTreeVo> getChildren(TypeTreeVo root, List<Zsfl> categoryList) {

        List<TypeTreeVo> list = categoryList.stream().filter(category ->
                        category.getSjflid().equals(root.getId())
                ).map(category -> {
                    TypeTreeVo typeTreeVo = new TypeTreeVo();
                    BeanUtils.copyProperties(category, typeTreeVo);

                    typeTreeVo.setChildren(getChildren(typeTreeVo, categoryList));
                    return typeTreeVo;
                })
                .collect(Collectors.toList());
        return list;
    }

}